<?php

class MysqliObj implements IDatabase {
	private static $_instance;
	
	private $_mysqli;
	
	public static function getInstance() {
		if (! (self::$_instance instanceof self)) {
			self::$_instance = new self ();
		}
		return self::$_instance;
	}
	
	private function __construct() {
		$db = Sysconfig::getDatabaseInfo ();
		$this->_mysqli = new mysqli ( $db ['host'], $db ['username'], $db ['password'], $db ['database'] );
		if (mysqli_connect_errno ()) {
			throw new Exception ( 'database' );
		}
		if (false === $this->_mysqli->set_charset ( "utf8" )) {
			throw new Exception ( 'set names utf8' );
		}
	}
	
	public function autocommit($mode) {
		return $this->_mysqli->autocommit ( $mode );
	}
	
	public function real_escape_string($sql) {
		return $this->_mysqli->real_escape_string ( $sql );
	}
	
	public function query($sql) {
		return $this->_mysqli->query ( $sql );
	}
	
	public function insert_id() {
		return $this->_mysqli->insert_id;
	}
	
	public function affected_rows() {
		return $this->_mysqli->affected_rows;
	}
	
	public function fetch_array($sql) {
		$result = $this->_mysqli->query ( $sql );
		if ($result) {
			return $result->fetch_assoc ();
		}
		return false;
	}
	
	public function fetch_arrays($sql) {
		$result = $this->_mysqli->query ( $sql );
		if ($result) {
			$array = array ();
			$row = $result->fetch_assoc ();
			while ( $row ) {
				$array [] = $row;
				$row = $result->fetch_assoc ();
			}
			$result->close ();
			return $array;
		}
		return false;
	}
	
	public function fetch_nums_arrays($sql) {
		if ($this->_mysqli->multi_query ( $sql . ";select found_rows() as allnums" )) {
			$array = array ();
			do {
				$result = $this->_mysqli->store_result ();
				if ($result) {
					$row = $result->fetch_assoc ();
					while ( $row ) {
						$array [] = $row;
						$row = $result->fetch_assoc ();
					}
					$result->free ();
				}
			} while ( $this->_mysqli->next_result () );
			return $array;
		}
		return false;
	}
	
	public function fetch_object($sql) {
		$result = $this->_mysqli->query ( $sql );
		return $result->fetch_object ();
	}
	
	public function fetch_list($sql) {
		$result = $this->_mysqli->query ( $sql );
		if ($result) {
			$array = array ();
			$row = $result->fetch_assoc ();
			while ( !empty ( $row ) ) {
				$array [] = $row;
				$row = $result->fetch_assoc ();
			}
			$result->close ();
			return $array;
		}
		return false;
	}
	
	public function get_errno() {
		return $this->_mysqli->errno;
	}
	
	public function get_error() {
		return $this->_mysqli->error;
	}
	
	public function commit() {
		return $this->_mysqli->commit ();
	}
	
	public function rollback() {
		return $this->_mysqli->rollback ();
	}
}